/// <license>
/// Copyright (c) 2002-2008, DotNetNuke Corporation
/// All rights reserved
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
/// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
/// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
/// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
/// of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
/// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
/// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
/// DEALINGS IN THE SOFTWARE.
/// </license>

using System;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.Localization;
using DNNSkin = DotNetNuke.UI.Skins.Skin;
using DotNetNuke.UI.Skins.Controls;

using DotNetNuke.ModuleToolkit.Localization;
using DotNetNuke.ModuleToolkit.Common;

namespace DotNetNuke.ModuleToolkit.Modules
{
    /// -----------------------------------------------------------------------------
    /// <summary>
    /// AdvancedModuleBase extends the core PortalModuleBase to provide Module Specific
    /// Helper Methods and Properties
    /// </summary>
    /// <history>
    /// 	[cnurse]	10/06/2007	Created
    /// </history>
    /// -----------------------------------------------------------------------------
    public class AdvancedModuleBase : 
        PortalModuleBase,
        ILocalizationService
    {

        #region Private Members

        private string messageKey = Null.NullString;

        #endregion

        #region Protected Properties

        /// <summary>
        /// IsAuthenticated determines whether the current user is authenticated
        /// </summary>
        protected bool IsAuthenticated
        {
            get { return (UserId > Null.NullInteger) ? true : false; }
        }

        /// <summary>
        /// MessageKey is a message localization key that can be passed between controls to inject a SkinMessage.  In the 
        /// localization resource file MessageKey.Text is the text of the message and MessageKey.Heading is the heading for the message.
        /// The icon displayed depends on the name of the key 
        ///   - if the key ends in "Success" - the Green success icon is used, 
        ///   - if the key ends in "Error" the Red error icon is used, 
        ///   - if the key ends in "Warning" the yellow warning icon is used
        /// </summary>
        protected string MessageKey
        {
            get { return messageKey; }
            set { messageKey = value; }
        }

        #endregion

        #region Public Properties

        /// <summary>
        /// ReturnUrl is the return Url for the control
        /// </summary>
        public virtual string ReturnURL
        {
            get
            {
                string returnUrl = Null.NullString;
                switch (Scope)
                {
                    case "":
                        if (String.IsNullOrEmpty(MessageKey))
                            returnUrl = Globals.NavigateURL();
                        else
                            returnUrl = Globals.NavigateURL(TabId, "", "Message=" + MessageKey);
                        break;
                }
                return returnUrl;
            }
        }

        /// <summary>
        /// Scope is a string that identifies thescope of the control - which is used by the ReturnUrl property
        /// to determine the appropriate control to return to.
        /// </summary>
        public string Scope
        {
            get
            {
                string scope = Null.NullString;
                if (Request.QueryString[Constants.PARAM_Scope] != null)
                    scope = Request.QueryString[Constants.PARAM_Scope];
                return scope;
            }
        }

        #endregion

        #region Protected Methods

        /// <summary>
        /// AddSkinMessage is a helper method that builds a "localized" message that can be added to the Skin
        /// </summary>
        /// <param name="key">The localization key that represents the message</param>
        /// <param name="type">The type of message to display</param>
        protected void AddSkinMessage(string key, ModuleMessage.ModuleMessageType type)
        {
            DNNSkin.AddModuleMessage(this, LocalizeString(key), type);
        }

        /// <summary>
        /// AddSkinMessage is a helper method that builds a "localized" message that can be added to the Skin
        /// </summary>
        /// <param name="key">The localization key that represents the message</param>
        /// <param name="headingKey">The localization key that represents the heading for the message</param>
        /// <param name="type">The type of message to display</param>
        protected void AddSkinMessage(string key, string headingKey, ModuleMessage.ModuleMessageType type)
        {
            DNNSkin.AddModuleMessage(this, LocalizeString(headingKey), LocalizeString(key), type);
        }

        /// <summary>
        /// AddSkinMessage is a helper method that builds a "localized" message that can be added to the Skin
        /// </summary>
        /// <param name="key">The localization key that represents the message</param>
        /// <param name="headingKey">The localization key that represents the heading for the message</param>
        protected void AddSkinMessage(string key, string headingKey)
        {
            AddSkinMessage(this, key, headingKey);
        }

        /// <summary>
        /// AddSkinMessage is a helper method that builds a "localized" message that can be added to the Skin
        /// </summary>
        /// <remarks>This overload determines the message type based on the key - if the key contains the word "success" then it is a Success
        /// message, if "error" then an Error message, if "warning" then a Warning message</remarks>
        /// <param name="control">The PortalModuleBase control that will host the Skin Message</param>
        /// <param name="key">The localization key that represents the message</param>
        /// <param name="headingKey">The localization key that represents the heading for the message</param>
        protected void AddSkinMessage(PortalModuleBase control, string key, string headingKey)
        {
            if (key.ToLower().Contains("success"))
                DNNSkin.AddModuleMessage(control, LocalizeString(headingKey), LocalizeString(key), ModuleMessage.ModuleMessageType.GreenSuccess);
            else if (key.ToLower().Contains("warning"))
                DNNSkin.AddModuleMessage(control, LocalizeString(headingKey), LocalizeString(key), ModuleMessage.ModuleMessageType.YellowWarning);
            else if (key.ToLower().Contains("error"))
                DNNSkin.AddModuleMessage(control, LocalizeString(headingKey), LocalizeString(key), ModuleMessage.ModuleMessageType.RedError);
        }

        /// <summary>
        /// ManageSecurity manages the security for the Module Controls
        /// </summary>
        /// <param name="securityCondition">The condition which if true will cause a message to be displayed</param>
        /// <param name="errorMessage">The message to be displayed</param>
        protected void ManageSecurity(bool securityCondition, string errorMessage)
        {
            if (!IsAuthenticated)
            {
                //User not Authenticated - Redirect to Access Denied
                Response.Redirect(Globals.AccessDeniedURL(LocalizeString("ModuleAccess.Error")), true);
            }
            else
            {
                if (securityCondition)
                {
                    //User registered - Redirect to main module page and display message
                    Response.Redirect(Globals.NavigateURL(TabId, "", "Message=" + errorMessage), true);
                }
            }
        }

        /// <summary>
        /// OnLoad runs when the control loads
        /// </summary>
        /// <remarks>OnLoad processes the Message token</remarks>
        /// <param name="e">An Event Args</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (!String.IsNullOrEmpty(Request.QueryString["Message"]))
            {
                string message = Request.QueryString["Message"];

                AddSkinMessage(message + ".Text", message + ".Heading");
            }
        }

        #endregion

        #region ILocalizationService Members

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Localizes the specified string.
        /// </summary>
        /// <param name="key">The string to localize</param>
        /// <history>
        ///     [anurse]  05/04/2006  created
        /// </history>
        /// -----------------------------------------------------------------------------
        public string LocalizeString(string key)
        {
            return LocalizeString(key, key, false);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Localizes the specified string.
        /// </summary>
        /// <param name="key">The string to localize</param>
        /// <param name="defaultValue">The value to return if the key can't be found</param>
        /// <history>
        ///     [anurse]  05/04/2006  created
        /// </history>
        /// -----------------------------------------------------------------------------
        public string LocalizeString(string key, string defaultValue)
        {
            return LocalizeString(key, defaultValue, false);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Localizes the specified string.
        /// </summary>
        /// <param name="key">The string to localize</param>
        /// <param name="defaultValue">The value to return if the key can't be found</param>
        /// <param name="useGlobalResources">A boolean specifying if global or local resources are to be used</param>
        /// <history>
        ///     [anurse]  05/04/2006  created
        ///     [anurse]  05/16/2006  added useGlobalResources parameter
        /// </history>
        /// -----------------------------------------------------------------------------
        public string LocalizeString(string key, string defaultValue, bool useGlobalResources)
        {
            string resourceFile = this.LocalResourceFile;
            if (useGlobalResources)
                resourceFile = global::DotNetNuke.Services.Localization.Localization.SharedResourceFile;

            string localized = global::DotNetNuke.Services.Localization.Localization.GetString(key, resourceFile);
            if (String.IsNullOrEmpty(localized))
                return defaultValue;
            else
                return localized;
        }

        #endregion


    }
}
